import { useState } from "react";
import md5 from "js-md5";
import { Form, Input, Button, MessagePlugin } from "tdesign-react";
import type { FormProps } from "tdesign-react";
import { useNavigate } from "react-router-dom";
import { connect } from "react-redux";
import { HOME_URL } from "@/config";
import { DesktopIcon, LockOnIcon } from "tdesign-icons-react";
import { setToken } from "@/redux/modules/global/action";
import { setTabsList } from "@/redux/modules/tabs/action";
import { useTranslation } from "react-i18next";
import loginData from "@data/login.json";

const { FormItem } = Form;
const LoginForm = (props: any) => {
	const { t } = useTranslation();
	const { setToken, setTabsList } = props;
	const navigate = useNavigate();
	const [form] = Form.useForm();
	const [loading, setLoading] = useState<boolean>(false);
	// 登录
	const onSubmit: FormProps["onSubmit"] = async e => {
		if (e.validateResult === true) {
			try {
				setLoading(true);
				const loginForm = e.fields;
				loginForm.password = md5(loginForm.password);
				const { data } = loginData;
				setToken(data?.access_token);
				navigate(HOME_URL);
				setTabsList([]);
				MessagePlugin.success("登录成功");
			} finally {
				setLoading(false);
			}
		}
	};
	const onReset: FormProps["onReset"] = e => {
		console.log(e);
		// MessagePlugin.info("重置成功");
	};
	return (
		<Form form={form} layout="vertical" onSubmit={onSubmit} onReset={onReset}>
			<FormItem
				label=""
				// help="这里请填写用户名"
				name="username"
				// initialData={"张三"}
				rules={[
					{ whitespace: true, message: t("login.usernameHold") },
					{ required: true, message: "用户名必填", type: "error" },
					{ min: 2, message: "至少需要两个字", type: "error" }
				]}
			>
				<Input prefixIcon={<DesktopIcon />} size="large" clearable={true} placeholder={t("login.usernameHold")} />
			</FormItem>
			<FormItem
				label=""
				// help="这里请填写密码"
				name="password"
				rules={[{ required: true, message: "密码必填", type: "error" }]}
			>
				<Input prefixIcon={<LockOnIcon />} type="password" size="large" clearable={true} placeholder={t("login.passwordHold")} />
			</FormItem>
			<FormItem>
				<div className="login-form-button">
					<Button type="reset" theme="default">
						{t("login.reset")}
					</Button>
					<Button type="submit" theme="primary" loading={loading}>
						{t("login.confirm")}
					</Button>
				</div>
			</FormItem>
		</Form>
	);
};

const mapDispatchToProps = { setToken, setTabsList };
export default connect(null, mapDispatchToProps)(LoginForm);
